package com.ruoyi.framework.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.ruoyi.common.core.domain.model.LoginUser;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyWebSocketHandler implements WebSocketHandler {

    // 存储所有活跃连接，key 可为 userId 或 sessionId
    private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 获取拦截器中保存的用户信息
        LoginUser loginUser = (LoginUser) session.getAttributes().get("loginUser");
        if (loginUser != null) {
            String userId = loginUser.getUserId().toString();
            sessions.put(userId, session);
            System.out.println("用户 " + loginUser.getUsername() + " 已连接，Session ID: " + session.getId());
        } else {
            session.close(CloseStatus.NOT_ACCEPTABLE);
        }
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        if (message instanceof TextMessage) {
            String payload = ((TextMessage) message).getPayload();
            System.out.println("收到消息: " + payload);

            // 回显测试
            session.sendMessage(new TextMessage("Server received: " + payload));
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("传输错误: " + exception.getMessage());
        session.close();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // 从会话池中移除
        LoginUser loginUser = (LoginUser) session.getAttributes().get("loginUser");
        if (loginUser != null) {
            String userId = loginUser.getUserId().toString();
            sessions.remove(userId);
            System.out.println("用户 " + loginUser.getUsername() + " 断开连接");
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}